<template>
  <div class="login-container">
        <span @click="clearCache">清除缓存</span>
    <div class="login-wrapper">
      <form class="login-form">
        <h3>医疗管理登录界面</h3>
        <div class="form-group">
          <input
            type="text"
            id="username"
            inputmode="text"
            v-model="loginForm.UserCode"
            required
            placeholder="请输入账号"
            @keyup.enter="handleGoKey"
            @click.stop="handleGoKey"
          />
        </div>
        <div class="form-group">
          <el-select
            v-model="site"
            placeholder="请选择站点"
            size="large"
          >
            <el-option
              v-for="item in options"
              :key="item.Site_ID"
              :label="item.Site_Name"
              :value="item.Site_ID"
            />
          </el-select>
        </div>
        <div class="form-group">
          <input
            type="password"
            id="password"
            inputmode="text"
            v-model="loginForm.UserPass"
            required
            placeholder="请输入密码"
            @keyup.enter="handleGoKey"
            @click.stop="handleGoKey"
          />
        </div>
        <el-button class="bn" @click="handleLogin">登录</el-button>
      </form>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios'; // 确保已经安装 axios
import { userStore } from '../stores/user.ts';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';

// Pinia 状态管理实例
const user = userStore();
const router = useRouter();

// 接口验证码
const Identification = ref('');

// 登录表单数据
const loginForm = ref({
  UserCode: '',
  UserPass: '',
});

// 全局站点
const site = ref('01');

// 选择站点数据列表
const options = ref([]);

// 请求获取选择站点数据列表
const getSite = () => {
  axios.post(window.globalUrl.server + 'Service.asmx/GetCheckSites', JSON.stringify({}))
    .then((res) => {
      console.log(JSON.parse(res.data.RltData));
      options.value = JSON.parse(res.data.RltData);
    })
    .catch((error) => {
      console.error(error);
    });
};
 const clearCache=()=> {
         if (confirm('确定要清除浏览器缓存记录吗？')) {
        // 清除 localStorage
        localStorage.clear();
        // 清除 sessionStorage
        sessionStorage.clear();
        // 清除 cookies
        document.cookie.split(";").forEach(function(cookie) { 
          document.cookie = cookie.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/");
        });

        // 清除 IndexedDB 数据库
        if (window.indexedDB) {
          const request = indexedDB.databases();
          request.onsuccess = function(event) {
            const databases = event.target.result;
            databases.forEach(db => {
              indexedDB.deleteDatabase(db.name);
            });
          };
        }

        // 清除 Service Worker 缓存
        if ('caches' in window) {
          caches.keys().then(keys => {
            keys.forEach(key => {
              caches.delete(key);
            });
          });
        }

        alert('缓存记录已清除');
        window.location.reload()
      }
    }
// 键盘事件按下 Enter 后触发的回调
const handleGoKey = (event) => {
  if (event.key === 'Enter') {
    // 关闭键盘
    event.target.blur();
  }
};

onMounted(() => {
  site.value = '01';
  getSite();
});

// 登录操作
const handleLogin = () => {
  axios.post(window.globalUrl.server + 'Service.asmx/CheckSysUser', JSON.stringify({
    UserCode: loginForm.value.UserCode,
    UserPass: loginForm.value.UserPass
  }))
    .then((res) => {
      console.log(res);
      console.log(res.data);
      if (JSON.parse(res.data.RltData).Stat_ID === 0) {
        Identification.value = JSON.parse(res.data.RltData).Interface_Code;
        sessionStorage.setItem('UserInfo', res.data.RltData);
        user.site = site.value;
        sessionStorage.setItem('st', JSON.stringify(site.value));
        sessionStorage.setItem('item', Identification.value);
        router.push('/tab');
        ElMessage.success({ message: '已完成登录' });
      } else {
        ElMessage.error({ message: '账号或密码不正确，请重试' });
      }
    })
    .catch((error) => {
      console.error(error);
    });
};
</script>

<style scoped>
*,
html,
body {
  margin: 0;
  padding: 0;
}

.login-container {
  width: 100%;
  height: 100vh;
  background-image: url("../assets/images/R-C (1).jpg");
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}
span{
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100px;
  height: 30px;
  position: fixed;
  right: 0;
  top: 0;
  background-color:whitesmoke;
  color: red;
  border-radius: 15px;
  font-size: 18px;
   box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.5);
  
}

.login-wrapper {
  width: 80%;
  max-width: 500px;
  position: absolute;
  height: 400px;
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}

.login-form {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.form-group {
  margin-bottom: 25px;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-sizing: border-box;
}

 ::v-deep .bn {
   width: 100%;
  height: 60px;
  background-color: #2ab9fc;
  color: #fdffff;
  border-radius: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 20px;
}

h3 {
  text-align: center;
  color: #242128;
  font-weight: bold;
  padding-bottom: 20px;
  font-family: Arial, Helvetica, sans-serif;
}

/* 横屏 iPad 设备 */
@media only screen 
  and (min-device-width: 768px) 
  and (max-device-width: 1024px) 
  and (-webkit-min-device-pixel-ratio: 2) 
  and (orientation: landscape) {
}

/* 竖屏 iPad 设备 */
@media screen and (orientation: portrait) {
  .login-container {
    background-size: cover;
  }

  .login-wrapper {
    max-width: 550px;
    height: 530px;
  }

  /* .el-button > span {
    font-size: 25px;
  } */

  .login-form button {
    height: 70px;
  }

  .form-group {
    margin-bottom: 50px;
  }
}
</style>